package com.lc.YYGH.msm.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.lc.YYGH.msm.service.MsmService;
import com.lc.YYGH.msm.utils.ConstantPropertiesUtils;
import com.lc.YYGH.vo.msm.MsmVo;
import com.zhenzi.sms.ZhenziSmsClient;
import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {
    @Override
    public boolean send(String phone,String code)
    {
        //判断手机号是否为空
        if(StringUtils.isEmpty(phone)) {
            return false;
        }
        String apiUrl= ConstantPropertiesUtils.API_URL;
        String appId=ConstantPropertiesUtils.APP_ID;
        String appSecret=ConstantPropertiesUtils.APP_SECRET;
        String templateId=ConstantPropertiesUtils.TEMPLATE_ID;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("number",phone);
        params.put("templateId",templateId);
        String[] templateParams= new String[2];
        templateParams[0]=code;
        templateParams[1]="2";
        params.put("templateParams",templateParams);
        ZhenziSmsClient client=new ZhenziSmsClient(apiUrl,appId,appSecret);
        try {
            String result = client.send(params);
           Map map= JSONObject.parseObject(result,Map.class); //将JSON格式的字符串转换成Map
          return map.get("data").toString().equals("发送成功");
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean send(MsmVo msmVo) {
        if(!StringUtils.isEmpty(msmVo.getPhone())){
            boolean isSend=this.send(msmVo.getPhone(),msmVo.getParam());
            return isSend;
        }
        return false;
    }
    private boolean send(String phone,Map<String,Object> param)
    {
        if(StringUtils.isEmpty(phone))
        {
            return false;
        }
        String apiUrl=ConstantPropertiesUtils.API_URL;
        String appId=ConstantPropertiesUtils.APP_ID;
        String appSecret=ConstantPropertiesUtils.APP_SECRET;
        String templateId="9073";
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("number",phone);
        params.put("templateId",templateId);
        String[] templateParams=new String[1];
        templateParams[0]=JSONObject.toJSONString(param);
        params.put("templateParams",templateParams);
        ZhenziSmsClient client=new ZhenziSmsClient(apiUrl,appId,appSecret);
        try{
            String result=client.send(params);
            Map map=JSONObject.parseObject(result,Map.class);
            return map.get("data").toString().equals("发送成功");

        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return false;

    }
}
